<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>实时天气展示</title>

</head>
<body>
<div class="weather-container">
    <div class="search-container">
        <button class="search-button" ><a href="/userApp/index" style="text-decoration: none;color: #fff">首页</a></button>
        <input type="text" class="search-box" id="cityInput" placeholder="输入城市名称">
        <button class="search-button" onclick="searchWeather()">查询</button>
    </div>
    <div class="time-display" id="currentTime">--</div>
    <div class="city-name" id="cityName">正在预测，请稍后...</div>

    <div class="temperature-container">
        <div class="temperature" id="temperature">--°C</div>
        <img class="weather-icon" id="weatherIcon" src="" alt="天气图标">
    </div>

    <div class="weather-description" id="weatherDescription">--</div>
    {#    <div class="weather-text-description" id="weatherTextDescription">--</div>#}

    <div class="weather-details">
        <div class="detail">
            <img src="../../static/static/weathericon/1.png" style="width: 20px;height: 20px">
            <div class="detail-label" style="margin-bottom: 5px">湿度</div>
            <div class="detail-value" id="humidity">--%</div>
        </div>
        <div class="detail">
            <img src="../../static/static/weathericon/2.png" style="width: 20px;height: 20px">
            <div class="detail-label" style="margin-bottom: 5px">降水量</div>
            <div class="detail-value" id="precipitation">--mm</div>
        </div>
        <div class="detail">
            <img src="../../static/static/weathericon/3.png" style="width: 20px;height: 20px">
            <div class="detail-label" style="margin-bottom: 5px">风力</div>
            <div class="detail-value" id="windForce">-- 级</div>
        </div>
        <div class="detail">
            <img src="../../static/static/weathericon/4.png" style="width: 20px;height: 20px">
            <div class="detail-label" style="margin-bottom: 5px">体感温度</div>
            <div class="detail-value" id="feelsLike">--</div>
        </div>
        <div class="detail">
            <img src="../../static/static/weathericon/5.png" style="width: 20px;height: 20px">
            <div class="detail-label" style="margin-bottom: 5px">大气压</div>
            <div class="detail-value" id="atmosphericPressure">-- hPa</div>
        </div>
        <div class="detail">
            <img src="../../static/static/weathericon/6.png" style="width: 20px;height: 20px">
            <div class="detail-label" style="margin-bottom: 5px">能见度</div>
            <div class="detail-value" id="vis">-- km</div>
        </div>
        <div class="detail">
            <img src="../../static/static/weathericon/7.png" style="width: 20px;height: 20px">
            <div class="detail-label" style="margin-bottom: 5px">风向</div>
            <div class="detail-value" id="windDirection">--</div>
        </div>
    </div>

    <div class="button-container">
        <button class="custom-button" onclick="showForecast()">天气预报</button>
        {#        <button class="custom-button" onclick="showPrediction()">天气预测</button>#}
        <!-- 将原showPrediction()调用改为 -->
        <button class="custom-button" onclick="showPrediction()">天气预测</button>
    </div>

    <div class="button-container">
        <button class="custom-button" onclick="showAlerts()">天气预警</button>
        <button class="custom-button" onclick="showSuggestions()">生活指数</button>
    </div>


    <div id="customModal" class="modal">
        <div class="modal-content">
            <span class="close">&times;</span>
            <h3 id="modalTitle"></h3>
            <p id="modalMessage"></p>
            <div id="chartContainer" style="width: 800px; height: 400px;"></div>
        </div>
    </div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/echarts/5.4.2/echarts.min.js"></script>
<script>
    // 和风天气 API 配置
    const HeweatherKey = '4e1ff199528745c790c3517457c64fa7'; // 替换为你的和风天气 API 密钥
    const HeweatherAPI = 'https://devapi.qweather.com/v7/weather/now';
    const GeocodeAPI = 'https://geoapi.qweather.com/v2/city/lookup';

    // 定义 forecastChart 变量
    let forecastChart;

    // 默认加载北京的天气
    document.addEventListener('DOMContentLoaded', function () {
        getWeatherByCity('北京');
    });

    // 查询天气函数
    function searchWeather() {
        const city = document.getElementById('cityInput').value.trim();
        if (city) {
            getWeatherByCity(city);
        }
    }

    // 获取天气数据
    async function getWeatherByCity(city) {
        try {
            const location = await getLocationByCity(city);
            console.log('Location data:', location); // 打印位置数据
            if (location) {
                const weatherData = await fetchWeatherData(location.id);
                console.log('Weather data:', weatherData); // 打印天气数据
                updateWeatherDisplay(weatherData, city);
            } else {
                alert('未找到该城市的位置信息');
            }
        } catch (error) {
            console.error('获取天气数据失败:', error);
            alert('获取天气数据失败，请稍后再试');
        }

        // 更新当前时间
        updateTime();
    }

    // 根据城市名称获取位置信息
    async function getLocationByCity(city) {
        const url = `${GeocodeAPI}?location=${encodeURIComponent(city)}&key=${HeweatherKey}`;
        console.log('请求的 URL:', url); // 打印请求的 URL
        const response = await fetch(url);
        console.log('Location response status:', response.status);
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        const data = await response.json();
        console.log('Location response data:', data);
        if (data.code === '200' && data.location) {
            return data.location[0];
        }
        return null;
    }

    // 获取天气数据
    async function fetchWeatherData(locationId) {
        const response = await fetch(`${HeweatherAPI}?location=${locationId}&key=${HeweatherKey}`);
        console.log('Weather response status:', response.status); // 打印响应状态
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        const data = await response.json();
        console.log('Weather response data:', data); // 打印天气响应数据
        if (data.code === '200') {
            return data.now;
        }
        throw new Error(data.code);
    }

    // 更新天气显示
    function updateWeatherDisplay(data, city) {
        document.getElementById('cityName').textContent = city;
        document.getElementById('temperature').textContent = data.temp + '°C';
        document.getElementById('weatherDescription').textContent = data.text;
        {#document.getElementById('weatherTextDescription').textContent = data.text;#}
        document.getElementById('humidity').textContent = data.humidity + '%';
        document.getElementById('precipitation').textContent = data.precip + 'mm';
        document.getElementById('windForce').textContent = data.windScale + ' 级';
        document.getElementById('feelsLike').textContent = data.feelsLike + ' ℃';

        {#document.getElementById('aqi').textContent = data.airQuality.aqi.china;#}
        document.getElementById('atmosphericPressure').textContent = data.pressure + ' hPa';
        document.getElementById('vis').textContent = data.vis + ' km';
        document.getElementById('windDirection').textContent = data.windDir;

        // 更新天气图标
        const iconMapping = {
            '晴': 'https://gd-hbimg.huaban.com/ed82dadc530e285a6a9c0dc6b535052f8efeb8c45e7cd-Ch5b5G_fw658webp',
            '多云': 'https://gd-hbimg.huaban.com/707267101f706c772d812cbc499111bd3046a4592b752-DdXRaI_fw658webp',
            '阴': 'https://gd-hbimg.huaban.com/a0102fd29040a762874b15bf41b94be0760447a235fa-pMMePh_fw658webp',
            '小雨': 'https://gd-hbimg.huaban.com/ab6a644714b5dae8cf3c7375e40aa5747fe8ac2d47c91-pLJmaw_fw658webp',
            '中雨': 'https://gd-hbimg.huaban.com/e68a2dfd582075e94dffafe65dc1fc2047a567fa10fb-6NSuo8_fw658webp',
            '大雨': 'https://gd-hbimg.huaban.com/da6b8d5cba9fe84e66a49eb43aa84fe054ac6f222a3ba-tZKVz7_fw658webp',
            '暴雨': 'https://gd-hbimg.huaban.com/44edec35a790dea3c562d739bb46577bd139a1482c44d-wzlYy3_fw658webp',
            '雷阵雨': 'https://gd-hbimg.huaban.com/df099ba044ef10348359387f752dcc2324bf7a532bdb4-mZIjQs_fw658webp',
            '雾': 'https://gd-hbimg.huaban.com/e2b8fee6101aae8c754f7b4b9193dbb16a5ffd8329b65-9vJ03f_fw658webp',
            '霾': 'https://gd-hbimg.huaban.com/5cf9c829b61b621db6c1d8214969eb140061027a7377-h6xJJI_fw658webp',
        };

        document.getElementById('weatherIcon').src = iconMapping[data.text] || iconMapping['default'] || 'https://cdn-icons-png.flaticon.com/512/6974/6974893.png';
    }

    // 更新当前时间
    function updateTime() {
        const now = new Date();
        const year = now.getFullYear();
        const month = now.getMonth() + 1;
        const day = now.getDate();
        const hours = now.getHours();
        const minutes = now.getMinutes();
        const seconds = now.getSeconds();

        const timeString = `${year}年${month}月${day}日${hours}:${minutes}:${seconds}`;
        document.getElementById('currentTime').textContent = timeString;
    }


    //天气预报

    // 修改7天预报API端点（使用devapi）
    async function fetch7DayForecast(locationId) {
        const url = `https://devapi.qweather.com/v7/weather/7d?location=${locationId}&key=${HeweatherKey}`; // 改为devapi
        const response = await fetch(url);
        console.log('7天预报响应状态:', response.status);
        if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);

        const data = await response.json();
        console.log('7天预报数据:', data);

        if (data.code === '200') return data.daily;
        throw new Error(data.code);
    }

    // 新增图表渲染函数
    function renderForecastChart(forecastData) {
        console.log("forecastData", forecastData)
        // 获取图表DOM元素
        const chartDom = document.getElementById('chartContainer');
        // 如果之前已经创建过图表，先销毁
        if (forecastChart) {
            echarts.dispose(forecastChart);
        }
        // 初始化图表
        forecastChart = echarts.init(chartDom);

        // 配置图表选项
        const option = {
            title: {
                {#text: '7天天气预报',#}
                left: 'center',
                textStyle: {
                    color: '#a8dadc'
                }
            },
            grid: {
                left: '10%'
            },
            legend: {
                data: ['最高温', '最低温'],
                // 设置图例位置
                right: '10%',  // 距离右侧10%的位置
                top: '2%',   // 距离顶部5%的位置
                textStyle: {
                    color: ['#ff6b6b', '#6b6bff'] // 设置图例文字颜色
                }
            },
            tooltip: {
                trigger: 'axis',
                formatter: function (params) {
                    const data = params[0];
                    return `日期：${data.name}<br/>
                            最高气温：${data.value}°C<br/>
                            最低气温：${data.data.tempMin}°C<br/>
                            天气状况：${data.data.textDay}`;
                }
            },
            xAxis: {
                type: 'category',
                data: forecastData.map(item => item.fxDate),
                axisLabel: {
                    color: '#fff',
                    formatter: function (value) {
                        return value.substr(0); // 显示MM-DD格式
                    }
                },
                axisLine: {
                    show: true,
                    lineStyle: {
                        color: '#fff'
                    }
                },
            },
            yAxis: {
                type: 'value',
                name: '温度 (°C)',

                axisLabel: {
                    textStyle: {
                        color: '#fff'
                    }
                },
                axisLine: {
                    show: true,
                    lineStyle: {
                        color: '#fff'
                    }
                },

                splitLine: {
                    lineStyle: {
                        color: '#1d3557'
                    }
                }
            },
            series: [
                {
                    name: '最高温',
                    type: 'line',
                    data: forecastData.map(item => ({
                        value: item.tempMax,
                        tempMin: item.tempMin,
                        textDay: item.textDay
                    })),
                    smooth: true,
                    symbol: 'circle',
                    symbolSize: 8,
                    itemStyle: {
                        color: '#ff6b6b'
                    },
                    lineStyle: {
                        width: 3
                    }
                },
                {
                    name: '最低温',
                    type: 'line',
                    data: forecastData.map(item => item.tempMin),
                    smooth: true,
                    symbol: 'circle',
                    // 原代码中此处缺失关闭括号和分号，补充完整
                    symbolSize: 8,
                    itemStyle: {
                        color: '#6b6bff'
                    },
                    lineStyle: {
                        width: 3
                    }
                }
            ]
        };

        // 使用配置项显示图表
        forecastChart.setOption(option);
    }

    // 显示天气预报的函数
    async function showForecast() {
        try {
            const city = document.getElementById('cityName').textContent;
            const location = await getLocationByCity(city);
            if (location) {
                const forecastData = await fetch7DayForecast(location.id);
                renderForecastChart(forecastData);
                // 显示模态框
                const modal = document.getElementById('customModal');
                const modalTitle = document.getElementById('modalTitle');
                const modalMessage = document.getElementById('modalMessage');
                modalTitle.textContent = `${city} 7天天气预报`;
                modalMessage.textContent = '';
                modal.style.display = 'block';

                // 关闭模态框的功能
                
                const closeBtn = document.querySelector('.close'); // 确保在此处定义
                closeBtn.onclick = function () {
                    const chartContainer = document.getElementById('chartContainer');
                    echarts.dispose(chartContainer);
                    modal.style.display = 'none';
                };

                window.onclick = function (event) {
                    if (event.target == modal) {
                        const chartContainer = document.getElementById('chartContainer');
                        echarts.dispose(chartContainer);
                        modal.style.display = 'none';
                    }
                };
            } else {
                alert('未找到该城市的位置信息');
            }
        } catch (error) {
            console.error('获取预报数据失败:', error);
            alert('获取预报数据频繁，请稍后再试');
        }
    }


    {#function showPrediction() {#}
    {#    showModal('天气预测', '基于AI模型的天气预测：\n下周将迎来持续高温天气，最高气温可能达到35°C');#}
    {# }#}

    {#function showPrediction() {#}
    {#    const city = document.getElementById('cityName').textContent;#}
    {##}
    {#    // 显示加载状态#}
    {#    const modal = document.getElementById('customModal');#}
    {#    modal.style.display = 'block';#}
    {#    document.getElementById('modalTitle').textContent = `${city} 天气预测`;#}
    {#    document.getElementById('chartContainer').innerHTML = '数据加载中...';#}
    {##}
    {#    // 发送AJAX请求#}
    {#    fetch('/userApp/weather_prediction/', {#}
    {#        method: 'POST',#}
    {#        headers: {#}
    {#            'Content-Type': 'application/x-www-form-urlencoded',#}
    {#            'X-CSRFToken': getCookie('csrftoken')#}
    {#        },#}
    {#        body: `city=${encodeURIComponent(city)}`#}
    {#    })#}
    {#        .then(response => response.json())#}
    {#        .then(data => {#}
    {#            if (data.status === 'success') {#}
    {#                renderPredictionChart(data.data);#}
    {#            } else {#}
    {#                alert('预测失败: ' + data.message);#}
    {#            }#}
    {#        });#}
    {#    // 关闭模态框的功能#}
    {#    // 获取关闭按钮#}
    {#    const closeBtn = document.querySelector('.close');#}
    {#    // 关闭模态框的功能#}
    {#    closeBtn.onclick = function () {#}
    {#        const chartContainer = document.getElementById('chartContainer');#}
    {#        // 先销毁图表实例，再隐藏模态框#}
    {#        echarts.dispose(chartContainer);#}
    {#        modal.style.display = 'none';#}
    {#    };#}
    {##}
    {#    window.onclick = function (event) {#}
    {#        if (event.target == modal) {#}
    {#            const chartContainer = document.getElementById('chartContainer');#}
    {#            // 先销毁图表实例，再隐藏模态框#}
    {#            echarts.dispose(chartContainer);#}
    {#            modal.style.display = 'none';#}
    {#        }#}
    {#    };#}
    {# }#}
    {##}
    {#function renderPredictionChart(predictions) {#}
    {#    const chartDom = document.getElementById('chartContainer');#}
    {##}
    {#    // 销毁现有图表实例#}
    {#    let existingChart = echarts.getInstanceByDom(chartDom);#}
    {#    if (existingChart) {#}
    {#        echarts.dispose(existingChart);#}
    {#    }#}
    {##}
    {##}
    {#    // 初始化新图表#}
    {#    const chart = echarts.init(chartDom);#}
    {##}
    {#    // 确保容器可见后执行#}
    {#    setTimeout(() => {#}
    {#        const option = {#}
    {#            title: {#}
    {#                text: '未来7天温度预测',#}
    {#                left: 'center',#}
    {#                textStyle: {#}
    {#                    color: '#a8dadc'  // 添加标题颜色#}
    {#                }#}
    {#            },#}
    {#            xAxis: {#}
    {#                type: 'category',#}
    {#                data: predictions.map(item => item.Date),#}
    {#                axisLabel: {#}
    {#                    color: '#fff'  // 添加x轴文字颜色#}
    {#                },#}
    {#                axisLine: {#}
    {#                    lineStyle: {#}
    {#                        color: '#fff'  // x轴线颜色#}
    {#                    }#}
    {#                }#}
    {#            },#}
    {#            yAxis: {#}
    {#                type: 'value',#}
    {#                name: '温度 (°C)',#}
    {#                axisLabel: {#}
    {#                    color: '#fff'  // y轴文字颜色#}
    {#                },#}
    {#                axisLine: {#}
    {#                    lineStyle: {#}
    {#                        color: '#fff'  // y轴线颜色#}
    {#                    }#}
    {#                },#}
    {#                splitLine: {#}
    {#                    lineStyle: {#}
    {#                        color: '#1d3557'  // 网格线颜色#}
    {#                    }#}
    {#                }#}
    {#            },#}
    {#            series: [{#}
    {#                data: predictions.map(item => item['Predicted Temp']),#}
    {#                type: 'line',#}
    {#                smooth: true,#}
    {#                itemStyle: {#}
    {#                    color: '#ff6b6b'#}
    {#                },#}
    {#                lineStyle: {#}
    {#                    width: 3#}
    {#                }#}
    {#            }],#}
    {#            grid: {#}
    {#                left: '10%'  // 避免y轴标签被截断#}
    {#            }#}
    {#        };#}
    {##}
    {#        chart.setOption(option);#}
    {#        chart.resize();  // 主动触发重绘#}
    {#    }, 100);  // 延迟100ms确保模态框动画完成#}
    {# }#}
    {##}
    {#// CSRF token获取函数#}
    {#function getCookie(name) {#}
    {#    let cookieValue = null;#}
    {#    if (document.cookie && document.cookie !== '') {#}
    {#        const cookies = document.cookie.split(';');#}
    {#        for (let i = 0; i < cookies.length; i++) {#}
    {#            const cookie = cookies[i].trim();#}
    {#            if (cookie.substring(0, name.length + 1) === (name + '=')) {#}
    {#                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));#}
    {#                break;#}
    {#            }#}
    {#        }#}
    {#    }#}
    {#    return cookieValue;#}
    {# }#}
    // 天气预测函数
    function showPrediction() {
        const city = document.getElementById('cityName').textContent;

        // 显示加载状态
        const modal = document.getElementById('customModal');
        modal.style.display = 'block';
        document.getElementById('modalTitle').textContent = `${city} 天气预测`;
        document.getElementById('chartContainer').innerHTML = '数据加载中...';

        // 发送AJAX请求
        fetch('/userApp/weather_prediction/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'X-CSRFToken': getCookie('csrftoken')
            },
            body: `city=${encodeURIComponent(city)}`
        })
        .then(response => response.json())
        .then(data => {
            if (data.status === 'success') {
                // 渲染预测图表
                renderPredictionChart(data.chart_data);
            } else {
                alert('预测失败: ' + data.message);
            }
        });
         // 关闭模态框的功能
        const closeBtn = document.querySelector('.close');
        closeBtn.onclick = function () {
            const chartContainer = document.getElementById('chartContainer');
                // 先销毁图表实例，再隐藏模态框
                echarts.dispose(chartContainer);
            modal.style.display = 'none';
        };

        window.onclick = function (event) {
            if (event.target == modal) {
                const chartContainer = document.getElementById('chartContainer');
                // 先销毁图表实例，再隐藏模态框
                echarts.dispose(chartContainer);
                modal.style.display = 'none';
            }
        };
    }

    // 渲染预测图表
    function renderPredictionChart(chart_data) {
        const chartDom = document.getElementById('chartContainer');
        const chart = echarts.init(chartDom);

        const option = {
            title: {
                text: '未来7天温度预测',
                left: 'center',
                textStyle: {
                    color: '#a8dadc'
                }
            },
            tooltip: {
                trigger: 'axis',
                formatter: function (params) {
                    const date = params[0].name;
                    const temp1 = params[0].value;
                    const temp2 = params[1].value;
                    return `日期：${date}<br/>
                            最高温度：${temp1}°C<br/>
                            最低温度：${temp2}°C`;
                }
            },
            legend: {
                data: ['最高温度', '最低温度'],
                right: '10%',
                top: '5%',
                textStyle: {
                    color: ['#ff6b6b', '#6b6bff']
                }
            },
            grid: {
                left: '10%',
                right: '10%',
                bottom: '10%',
                top: '20%',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                data: chart_data.dates,
                axisLine: {
                    lineStyle: {
                        color: '#fff'
                    }
                },
                axisLabel: {
                    color: '#fff'
                }
            },
            yAxis: {
                type: 'value',
                name: '温度 (°C)',
                axisLine: {
                    lineStyle: {
                        color: '#fff'
                    }
                },
                axisLabel: {
                    color: '#fff'
                },
                splitLine: {
                    lineStyle: {
                        color: '#1d3557'
                    }
                }
            },
            series: [
                {
                    name: '最高温度',
                    type: 'line',
                    data: chart_data.temp1,
                    smooth: true,
                    symbol: 'circle',
                    symbolSize: 8,
                    itemStyle: {
                        color: '#ff6b6b'
                    },
                    lineStyle: {
                        width: 3
                    }
                },
                {
                    name: '最低温度',
                    type: 'line',
                    data: chart_data.temp2,
                    smooth: true,
                    symbol: 'circle',
                    symbolSize: 8,
                    itemStyle: {
                        color: '#6b6bff'
                    },
                    lineStyle: {
                        width: 3
                    }
                }
            ]
        };

        chart.setOption(option);
        chart.resize();

       
    }

    // CSRF token获取函数
    function getCookie(name) {
        let cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            const cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                const cookie = cookies[i].trim();
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }


    // 天气预警API配置
    const WarningAPI = 'https://devapi.qweather.com/v7/warning/now';

    // 显示天气预警的函数
    async function showAlerts() {
        try {
            const city = document.getElementById('cityName').textContent;
            const location = await getLocationByCity(city);
            if (!location) {
                showModal('天气预警', '无法获取城市位置信息');
                return;
            }

            const warningData = await fetchWarningData(location.id);
            if (!warningData || warningData.length === 0) {

                // 如果没有预警数据，显示“暂无预警”
                const modal = document.getElementById('customModal');
                const modalTitle = document.getElementById('modalTitle');
                const modalMessage = document.getElementById('modalMessage');
                const chartContainer = document.getElementById('chartContainer');

                chartContainer.innerHTML = ''; // 清空折线图容器
                modalTitle.textContent = `${city} 天气预警`;
                modalMessage.textContent = '暂无预警';
                modal.style.display = 'block';

                // 关闭模态框的功能
                const closeBtn = document.querySelector('.close');
                closeBtn.onclick = function () {
                    modal.style.display = 'none';
                };

                window.onclick = function (event) {
                    if (event.target == modal) {
                        modal.style.display = 'none';
                    }
                };

            } else {

                // 在模态框中展示天气预警数据
                const modal = document.getElementById('customModal');
                const modalTitle = document.getElementById('modalTitle');
                const modalMessage = document.getElementById('modalMessage');
                // 清空折线图容器
                chartContainer.innerHTML = '';

                modalTitle.textContent = `${city} 天气预警`;
                chartContainer.innerHTML = formatWarningData(warningData);
                modal.style.display = 'block';

                // 关闭模态框的功能
                const closeBtn = document.querySelector('.close');
                closeBtn.onclick = function () {
                    modal.style.display = 'none';
                };

                window.onclick = function (event) {
                    if (event.target == modal) {
                        modal.style.display = 'none';
                    }
                };
            }
        } catch (error) {
            console.error('获取预警数据失败:', error);
            showModal('天气预警', `获取预警数据失败，请稍后重试`);
        }
    }

    // 获取天气预警数据
    async function fetchWarningData(locationId) {
        const url = `${WarningAPI}?location=${locationId}&key=${HeweatherKey}`;
        const response = await fetch(url);
        console.log('天气预警响应状态:', response.status);
        if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);

        const data = await response.json();
        console.log('天气预警数据:', data);

        if (data.code === '200') return data.warning;
        throw new Error(data.code);
    }

    // 格式化天气预警数据
    function formatWarningData(warningData) {
        let formattedData = '';
        warningData.forEach(warning => {
            formattedData += `<div class="warning-item">
                            
                            <h4>${warning.title}</h4>
                            <img src="https://gd-hbimg.huaban.com/38194e1b425926e09786a0b776df8aeb19fe6a2add2ef-8Wh1FH" alt="天气预警" style="width: 100px;height: 100px">
                            <p>发布单位：${warning.sender}</p>
                            <p>发布时间：${warning.pubTime}</p>
                            <p style="width: 750px">预警内容：${warning.text}</p>
                          </div>`;
        });
        return formattedData;
    }


    //生活指数
    // 在API配置部分添加生活指数接口
    const LivingAPI = 'https://devapi.qweather.com/v7/indices/1d';

    // 修改生活建议点击处理函数
    async function showSuggestions() {
        try {
            const city = document.getElementById('cityName').textContent;
            const location = await getLocationByCity(city);
            if (!location) {
                showModal('生活建议', '无法获取城市位置信息');
                return;
            }

            const indicesData = await fetchLivingIndices(location.id);
            {#if(!indicesData||indicesData.length==0)#}
            const modal = document.getElementById('customModal');
            const modalTitle = document.getElementById('modalTitle');
            const modalMessage = document.getElementById('modalMessage');
            const chartContainer = document.getElementById('chartContainer');
            modalMessage.innerHTML = ''; // 清空
            // 清空图表容器
            chartContainer.innerHTML = '';

            // 创建建议内容
            {#        const suggestionsHTML = indicesData.map(item => `#}
            {#    <div class="suggestion-item">#}
            {#        #}
            {#        <h4>${item.name}（${item.category}）</h4>#}
            {#        <p>${item.text}</p>#}
            {#    </div>#}
            {#`).join('');#}
            const suggestionsHTML = indicesData.map(item => {
                // 构造图片路径
                const imgPath = `../../static/生活指数/${item.type}.png`;
                return `
                <div class="suggestion-item" style="width: 195px;margin-left: 20px" title="${item.text}">
                   
                    <img src="${imgPath}" alt="${item.name}" title="${item.text}" style="width: 50px; height: 50px;" >
                    <h5>${item.name}（${item.category}）</h5>
                </div>
            `;
            }).join('');


            modalTitle.textContent = `${city} 生活指数`;
            chartContainer.innerHTML = suggestionsHTML;
            modal.style.display = 'block';

            // 关闭逻辑
            document.querySelector('.close').onclick = () => modal.style.display = "none";
            window.onclick = (event) => {
                if (event.target == modal) modal.style.display = "none";
            }

        } catch (error) {
            console.error('获取生活指数失败:', error);
            {#showModal('生活建议', '获取生活建议失败，请稍后重试');#}
        }
    }

    // 新增生活指数API请求函数
    async function fetchLivingIndices(locationId) {
        const url = `${LivingAPI}?location=${locationId}&key=${HeweatherKey}&type=1,2,3,5,6,8,9,10,13`;
        const response = await fetch(url);
        console.log('生活指数响应状态:', response.status);
        if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);

        const data = await response.json();
        console.log('生活指数数据:', data);

        if (data.code === '200') return data.daily;
        throw new Error(data.code);
    }


</script>
</body>
<style>
    /* 添加模态框样式 */
    .modal {
        display: none;
        position: fixed;
        z-index: 9999;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.5);
    }

    .modal-content {
        background-color: #0d1b2a;
        margin: 5% auto;
        padding: 20px;
        border: 1px solid #1d3557;
        width: 50%;
        border-radius: 8px;
        color: white;
        position: relative;
    }


    {##chartContainer {#}
    {#    margin-top: 20px;#}
    {# }#}
    #chartContainer {
        display: flex;
        flex-wrap: wrap; /* 允许换行 */
        margin-top: 20px;
    }

    .suggestion-item {
    {#flex: 1 1 33%; /* 每个 item 占据 33% 的宽度，每行最多 3 个 */#} padding: 15px;
        margin: 5px;
        background: rgba(255, 255, 255, 0.1);
        border-radius: 8px;
        min-width: 100px; /* 设置最小宽度，避免在小屏幕上 item 过窄 */
    }

    .close {
        color: #aaa;
        float: right;
        font-size: 28px;
        font-weight: bold;
    }

    .close:hover,
    .close:focus {
        color: #e63946;
        text-decoration: none;
        cursor: pointer;
    }

    #modalTitle {
        color: #a8dadc;
        border-bottom: 1px solid #457b9d;
        padding-bottom: 10px;
    }

    #modalMessage {
        margin-top: 15px;
        line-height: 1.6;
    }

    body {
        font-family: 'Arial', sans-serif;
        margin: 0;
        padding: 0;
        display: flex;
        justify-content: center;
        align-items: center;
        height: 100vh;
    {#background: linear-gradient(to bottom, #c0def5, #f3f2f6); /* 从浅紫到浅橙的渐变背景 */#}{#background: linear-gradient(to bottom, #acdcfc, #f8f0d6); /* 从浅紫到浅橙的渐变背景 */#} background: linear-gradient(to bottom, #e1e1fa, #fff8e1); /* 从浅紫到浅橙的渐变背景 */
    }

    .weather-container {
        background-color: rgba(255, 255, 255, 0.2); /* 半透明背景 */
        border-radius: 10px;
        box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
        padding: 30px;
        width: 900px;
        text-align: center;
    }

    .time-display {
        font-size: 16px;
        color: #666;
        margin-bottom: 10px;
        margin-top: 10px;
    }

    .city-name {
        font-size: 24px;
        font-weight: bold;
        margin-bottom: 10px;
        color: #333;
    }

    .temperature-container {
        display: flex;
        align-items: center;
        justify-content: center;
        margin-bottom: 20px;
    }

    .temperature {
        font-size: 48px;
        font-weight: bold;
        color: #ff6b6b;
        margin-right: 20px;
    }

    .weather-icon {
        width: 100px;
        height: 100px;
    }

    .weather-description {
        font-size: 18px;
        margin-bottom: 10px;
        color: #555;
    }

    .weather-text-description {
        font-size: 16px;
        color: #666;
        margin-bottom: 20px;
    }

    .weather-details {
        display: flex;
        justify-content: space-around;
        margin-top: 20px;
        flex-wrap: wrap;
    }

    .detail {
        text-align: center;
        margin: 10px;
    }

    .detail-label {
        font-size: 16px;
        color: #777;
    }

    .detail-value {
        font-size: 14px;
        font-weight: bold;
        color: #333;
    }

    .search-container {
        margin-top: 20px;
    }

    .search-box {
        padding: 10px;
        width: 70%;
        border: 1px solid #ddd;
        border-radius: 4px;
        font-size: 16px;
    }

    .search-button {
        padding: 10px 15px;
        background-color: #4CAF50;
        color: white;
        border: none;
        border-radius: 4px;
        cursor: pointer;
        font-size: 16px;
    }

    .search-button:hover {
        background-color: #45a049;
    }

    .button-container {
        display: flex;
        justify-content: space-around;
        margin-top: 20px;
    }

    .custom-button {
        padding: 10px 15px;
        background-color: #a6bcf1;
    {#background-color: #83a4f3;#} color: white;
        border: none;
        border-radius: 4px;
        cursor: pointer;
        font-size: 16px;
        width: 45%;
    }

    .custom-button:hover {
        background-color: #becef1;
    }

    .forecast-container {
        margin-top: 20px;
        display: none;
    }

    .forecast-item {
        display: flex;
        align-items: center;
        margin: 10px 0;
    }

    .forecast-date {
        width: 40px;
        text-align: center;
        font-weight: bold;
    }

    .forecast-icon {
        width: 30px;
        height: 30px;
        margin: 0 10px;
    }

    .forecast-temp {
        flex-grow: 1;
    }

    .alert-container, .suggestion-container {
        margin-top: 20px;
        display: none;
    }

    .alert-item, .suggestion-item {
        padding: 10px;
        background-color: #fff8dc;
        border-left: 4px solid #ff6b6b;
        margin-bottom: 10px;
    }

    /* 添加生活建议样式 */
    .suggestion-item {
        padding: 15px;
        margin: 10px 0;
        background: rgba(255, 255, 255, 0.1);
        border-radius: 8px;
    }

    .suggestion-item h4 {
        color: #a8dadc;
        margin: 0 0 10px 0;
        font-size: 16px;
    }

    .suggestion-item p {
        color: #fff;
        margin: 0;
        line-height: 1.5;
    }

    #chartContainer {
        max-height: 400px;
        overflow-y: auto;
    }
</style>
</html>